package com.eurasia.assignment.infrastructure.client.hoj.auth;

import com.eurasia.assignment.service.port.out.FetchHOJAuthorizationPort;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
@Log4j2
public class HOJAuthClientAdapter implements FetchHOJAuthorizationPort {

    private final HOJLoginFeignClient hojLoginFeignClient;

    @Override
    public String fetchHOJAuthorization() {
        // 从环境变量读取账号密码
        if (System.getenv("HOJ_USERNAME") == null || System.getenv("HOJ_PASSWORD") == null) {
            throw new RuntimeException("HOJ_USERNAME or HOJ_PASSWORD is not set");
        }
        log.debug("HOJ_USERNAME: " + System.getenv("HOJ_USERNAME"));
        ResponseEntity<String> response = hojLoginFeignClient.login(LoginRequest.builder()
                .username(System.getenv("HOJ_USERNAME"))
                .password(System.getenv("HOJ_PASSWORD"))
                .build());

        return response.getHeaders().getFirst("authorization");
    }
}
